<?php

namespace front\modules\web\controllers;
use common\helpers\ReturnHelper;
use EasyWeChat\User\User;
use order\models\Orders;
use users\models\CustomerInfo;
use users\services\RegionService;
use wechat\models\Account;
use wechat\services\AccountService;
use wechat\services\PaymentService;
use Yii;
use yii\data\ActiveDataProvider;
use front\controllers\WebBaseController;
use yii\web\NotFoundHttpException;
use yii\filters\VerbFilter;
use order\services\OrderService;
use goods\services\ProductService;
use yii\helpers\ArrayHelper;
use goods\services\CartService;
use order\services\OrderUserService;
use coupons\services\CouponsGroupService;
use backend\services\ShopService;
use coupons\services\CouponsService;
use EasyWeChat\Foundation\Application;
use EasyWeChat\Payment\Order;
use EasyWeChat\Support\Url;
use yii\web\Cookie;


/**
 * OrderController implements the CRUD actions for OrderModel model.
 */
class OrderController extends WebBaseController
{
    //public $layout = 'main';

    private $_appId = '';

    private $_appSecret = '';

    private $_mch_id = '';

    private $_mch_key = '';

    public function behaviors()
    {
        return [
            'verbs' => [
                'class' => VerbFilter::className(),
                'actions' => [
                    'delete' => ['post'],
                ],
            ],
        ];
    }

    public function init()
    {
        parent::init();

        $wxpayRes = PaymentService::getPaymentConf();
        $wxpayRes = $wxpayRes['result'];
        $this->_appId = $wxpayRes['appId'];//'wxb92c2bb9c487c950';
        $this->_appSecret = $wxpayRes['appSecret'];//'4531c2e3fcf9438320af5cb85b068549';
        $this->_mch_id = $wxpayRes['mch_id'];//'1301495501';
        $this->_mch_key = $wxpayRes['mch_key'];//'Yk3Bn8sBsg2yJ83gfkKHgfehe7Hdggsk';
    }
    /**
     * 订单购买页面
     *   $data= array(
            0=>  array('product_id'=> '1600034','num'=>'1','data'=> '颜色: 灰色','price'=>'123'),
            1=>  array('product_id'=> '1000007','num'=>'1','data'=> '颜色: 灰色','price'=>'123'),
          );
     */
    function actionBuy(){
        $this->layout=false;
        if($this->getUserId() == 0){
            return $this->redirect('/web/user/login');
        }
        $orderPost = yii::$app->request->post();

        //post提交过来的参数
        if($orderPost){
            $cookies = \Yii::$app->response->cookies;
            $cookies->add(new Cookie([
                'name' => 'order',
                'value' => json_encode($orderPost),
            ]));
        }else{
            //get过来读取的cookie
            $jsonOrder = Yii::$app->request->cookies->getValue('order');
            $orderPost = json_decode($jsonOrder,true);
            if(!$orderPost){
                return $this->redirect('/web/order/index');
            }
        }

            $orderPost['hide_buy'] = isset($orderPost['hide_buy']) ? $orderPost['hide_buy']:'';
            //------------------------
            $total_price = $count = 0;
            $data=$groupInfo=[];
            $retailerId = isset($orderPost['retailerId'])&&$orderPost['retailerId'] ? $orderPost['retailerId']:'';

            //商品id用户卡券
            $product_id=[];
            if(isset($orderPost['product_id'])&&$orderPost['product_id']){
                //查看购物车里的数量
                $cartNum = CartService::oneProductCount($this->shop_id,$this->getUserId(),$orderPost['product_id']);
                //直接购买
                $data[0]['product_id'] = $orderPost['product_id'];
                $data[0]['shop_id'] =$this->shop_id;
                $data[0]['num'] = $orderPost['num'] + $cartNum;
                $productInfo = ProductService::ProductInfo($orderPost['product_id']);
                $productInfo['result'] = ArrayHelper::toArray($productInfo['result']);
                if($productInfo['result']['productInfo']['stock']<=0 || $productInfo['result']['productInfo']['stock']<$data[0]['num']){
                    return "<script language='JavaScript'>alert('库存不足');window.location.href='/web/product/detail?pid=" . $orderPost['product_id'] . "';</script>";
                }


                $data[0]['data']['item_attrText_map'] = isset($productInfo['result']['productInfo']['item_attrText_map']) ? $this->setAttrOrder($productInfo['result']['productInfo']['item_attrText_map']) : '';
                $data[0]['price'] = isset($productInfo['result']['productInfo']['price'])? $productInfo['result']['productInfo']['price']:'0.00';
                $data[0]['name'] =$productInfo['result']['productInfo']['name'];
                $data[0]['data']['thumb'] =$productInfo['result']['productInfo']['thumb'][0]. '@1e_1c_0o_0l_200h_200w_100q.jpg';
                $total_price += ($data[0]['price'] * $data[0]['num']);
                $count += $data[0]['num'];
                $product_id[] = $orderPost['product_id'];
            }

            if($retailerId){
                $res = $this->getOrder($retailerId);
                //购买之后不付款，支付返回
                //购物车产品信息
                foreach($res as $v){
                    $cartInfo[] = CartService::oneInfo($v['shop_id'],$this->getUserId(),$v['product_id']);
                }
                if(!$cartInfo[0]){
                    return $this->redirect('/web/order/index');
                }

                foreach($cartInfo as $k=>$v){
                    $data[$k]['product_id'] = $v['product_id'];
                    $data[$k]['shop_id'] = $v['shop_id'];
                    $data[$k]['num'] = $v['num'];
                    $goodsinfo[$k]= ProductService::ProductInfo($v['product_id']);
                    $goodsinfo[$k]['result'] = ArrayHelper::toArray($goodsinfo[$k]['result']);
                    if($goodsinfo[$k]['result']['productInfo']['stock']<=0 || $goodsinfo[$k]['result']['productInfo']['stock']<$v['num']){
                        return "<script language='JavaScript'>alert('". $goodsinfo[$k]['result']['productInfo']['name'] ."库存不足');window.location.href='/web/cart/view';</script>";
                    }

                    $data[$k]['price'] = isset($goodsinfo[$k]['result']['productInfo']['price']) ? $goodsinfo[$k]['result']['productInfo']['price'] :'0.00';
                    $data[$k]['data']['thumb'] = isset($goodsinfo[$k]['result']['productInfo']['thumb'][0])?$goodsinfo[$k]['result']['productInfo']['thumb'][0]. '@1e_1c_0o_0l_200h_200w_100q.jpg':"";
                    $data[$k]['name'] = isset($goodsinfo[$k]['result']['productInfo']['name']) ? $goodsinfo[$k]['result']['productInfo']['name'] :'';
                    $data[$k]['data']['item_attrText_map'] = isset($goodsinfo[$k]['result']['productInfo']['item_attrText_map']) ?
                        $this->setAttrOrder($goodsinfo[$k]['result']['productInfo']['item_attrText_map']) : '';
                    $total_price += ($data[$k]['price'] * $data[$k]['num']);
                    $count += $data[$k]['num'];
                    $product_id[] = $v['product_id'];

                }

            }

        //获取用户是否有卡券
        $couponsInfo = CouponsService::couponsInfo($product_id,$this->getUserId()) ?  CouponsService::couponsInfo($product_id,$this->getUserId()) : [];
        if($couponsInfo){
            foreach($couponsInfo as $k=>$v){
                $userCoupons = CouponsGroupService::getGroupInfo($v);
                $couponsInfo = ArrayHelper::toArray($userCoupons['result'][0]);
            }

            //当订单总金额小于卡券，就不显示
            if(isset($couponsInfo['voucher'])){
                $must_voucher_price = $couponsInfo['voucher']['must_voucher_price']&&$couponsInfo['voucher']['must_voucher_price'] ? $couponsInfo['voucher']['must_voucher_price']:0;
                if($total_price < $must_voucher_price){
                    $couponsInfo='';
                }
            }
        }else{
            $couponsInfo='';
        }




        $list['total_price'] = isset($total_price) ? WebBaseController::price_format($total_price) : 0 ;
        $list['count'] = isset($count) ? $count : 0 ;
        $list['product'] = isset($data) ? $data : [] ;
        //用户线上购买地址
        $res['user_id'] = $this->getUserId();
        $res['getByWeb']=1;

        //选择收货地址
        if(Yii::$app->request->get('addr_id')){
            $res['id'] = Yii::$app->request->get('addr_id'); //1是默认地址 0不是
        }else{
            $defaddress = OrderUserService::search($res);
            $deladdressInfo = ArrayHelper::toArray($defaddress['result']);
            if(isset($deladdressInfo)&&$deladdressInfo){
                //1是默认地址 0不是
                $arr=[];
                foreach($deladdressInfo as $k=>$v){
                    $arr[] = isset($v['default'])?$v['default']:array();
                }
                if(isset($arr)&&$arr){
                    if(count($arr)>0&&count($arr)<2){
                        $res['default'] = $arr[0];
                    }else{
                        if(in_array(1,$arr)){
                            $res['default'] = 1;
                        }
                    }
                }

            }
        }

        //用户默认地址
        $userSite = OrderUserService::search($res);
        $address = ArrayHelper::toArray($userSite['result']);
        if($address){
            if(isset($address[0]['district'])&&$address[0]['district']==0){
                $address[0]['merger']=$address[0]['dist_cn_char'];
                $address[0]['address'] = isset( $address[0]['merger'])&&isset($address[0]['address'])? $address[0]['merger']. $address[0]['address']:"";
            }else{
                $addrRes = isset($address[0]['district']) ? self::getDistrict_char($address[0]['district']):'';
                $address[0]['district_char'] = isset($addrRes['district_char'])?$addrRes['district_char']:"";
                $address[0]['merger'] = isset($addrRes['merger']) ? $addrRes['merger']:'';
                $address[0]['address'] = isset($addrRes['merger'])&&isset($address[0]['address'])?$addrRes['merger']. $address[0]['address']:"";
            }

        }

        if($address){
            $cookies = \Yii::$app->response->cookies;
            $cookies->add(new Cookie([
                'name' => 'addressinfo',
                'value' => json_encode($address),
            ]));
        }else{
            //get过来读取的cookie
            $jsonAddr = Yii::$app->request->cookies->getValue('addressinfo');
            $address = json_decode($jsonAddr,true);
        }

        $list['user_site'] =  $address;

        //刷新地址，显示备注
        $remark = Yii::$app->request->cookies->getValue('remark') ? Yii::$app->request->cookies->getValue('remark') : '';
        $onlinepay = Yii::$app->request->cookies->getValue('onlinepay') ? Yii::$app->request->cookies->getValue('onlinepay') : '';

        //刷新显示自提地址
        $selfAddr = Yii::$app->request->cookies->getValue('addr') ?  Yii::$app->request->cookies->getValue('addr') : '';
        $selfMobile =    Yii::$app->request->cookies->getValue('mobile') ? Yii::$app->request->cookies->getValue('mobile') : '';
        $selfAddrInfo = '';
        $selfAddrInfo .= '线下地址:'.$selfAddr.':联系方式:'.$selfMobile;

        //是快递还是自提
        $selfDelivery = Yii::$app->request->cookies->getValue('delivery') ?  Yii::$app->request->cookies->getValue('delivery') : '';
        $selfPersonal = Yii::$app->request->cookies->getValue('selfpersonal') ?  Yii::$app->request->cookies->getValue('selfpersonal') : '';

        //是工作日还是周末
        $workDay = Yii::$app->request->cookies->getValue('workday') ?  Yii::$app->request->cookies->getValue('workday') : '';
        $weekDay = Yii::$app->request->cookies->getValue('weekday') ?  Yii::$app->request->cookies->getValue('weekday') : '';

        //卡券信息

        $couponsVal = Yii::$app->request->cookies->getValue('voucher') ?  Yii::$app->request->cookies->getValue('voucher') : 0;
        $couponsId = Yii::$app->request->cookies->getValue('conpons_id') ?  Yii::$app->request->cookies->getValue('conpons_id') : 0;


        //将总价放入cookie
        if($list['total_price']){
            $cookies = \Yii::$app->response->cookies;
            $cookies->add(new Cookie([
                'name' => 'total_price',
                'value' => WebBaseController::price_format($list['total_price']),
            ]));
        }else{
            //get过来读取的cookie
            $jsonTotal = Yii::$app->request->cookies->getValue('total_price');
            $list['total_price'] = $jsonTotal;
        }


        return  $this->render('buy',[
            'list'=>$list,
            'coupons' => isset($groupInfo) ? $groupInfo : '' ,
            'appId'=>'wxb92c2bb9c487c950',
            'hide_buy'=> isset($orderPost['hide_buy']) ? $orderPost['hide_buy'] : '',
            'uid' =>$this->getUserId(),
            'remark'=>$remark,
            'onlinepay'=>$onlinepay,
            'selfaddrInfo' =>$selfAddrInfo,
            'selfaddr'=>$selfAddr,
            'selfDelivery' =>$selfDelivery,
            'selfPersonal'=>$selfPersonal,
            'workDay' =>$workDay,
            'weekDay'=>$weekDay,
            'userCoupons'=>$couponsInfo,
            'product_id'=>$product_id,
            'couponsVal'=>$couponsVal,
            'couponsId'=>$couponsId
        ]);
    }

    function actionAddaddr(){

        $this->layout=false;
        if (Yii::$app->request->isAjax) {
            $getPost = yii::$app->request->post();
            $getPost['default'] = 1;
            $getPost['district'] = 0;
            $getPost['user_id'] = $this->getUserId();
            $result = OrderUserService::addAddress($getPost);
            return json_encode($result);
        }

        $res['user_id'] = $this->getUserId();
        $res['getByWeb']=1;
        $res['status']=1;
        //用户默认地址
        $userSite = OrderUserService::search($res);
        if(isset($userSite)){
            $address = ArrayHelper::toArray($userSite['result']);
            foreach($address as $k=>$v){
                if(isset($v['district'])&&$v['district']==0){
                    $address[$k]['merger']=$v['dist_cn_char'];
                    $address[$k]['district_char'] = '';
                    $address[$k]['address'] = isset($v['dist_cn_char'])&&isset($v['address'])? $v['dist_cn_char']. $v['address']:"";
                }else{
                    $addrRes = isset($v['district']) ? self::getDistrict_char($v['district']):'';
                    $address[$k]['district_char'] = isset($addrRes['district_char'])?$addrRes['district_char']:"";
                    $address[$k]['merger'] = isset($addrRes['merger']) ? $addrRes['merger']:'';
                    $address[$k]['address'] = isset($addrRes['merger'])&&isset($address[$k]['address'])?$addrRes['merger']. $address[$k]['address']:"";
                }

            }
        }


// 定义参数
        $configForPickAddress = \Yii::$app->request->cookies->getValue('configForPickAddress');
        if(empty($configForPickAddress)){
            $app = new Application([
                'app_id'  => 'wxb92c2bb9c487c950',         // AppID
                'secret'  => '4531c2e3fcf9438320af5cb85b068549',     // AppSecret
                'payment' => [
                    'merchant_id'        => '1301495501',
                    'key'                => 'Yk3Bn8sBsg2yJ83gfkKHgfehe7Hdggsk',
                ]
            ]);

            if (empty($_GET['code'])) {
                $currentUrl = Url::current();  // 获取当前页 URL
                $response = $app->oauth->scopes(['snsapi_base'])->redirect($currentUrl);
                $response->send(); // or echo $response;
            }
            // 授权回来
            /** @var User $user */

            if(empty($_SESSION['user'])|| empty($_SESSION['access_token'])){
                $user = $app->oauth->user();
                Yii::$app->session->set('user',$user);
            }else{
                $user = Yii::$app->session->get('user');
            }

            $token = $user->getAccessToken();
            $access_token = $token->getToken();
            Yii::$app->session->set('access_token',$access_token);
            $payment = $app->payment;
            $configForPickAddress = $payment->configForShareAddress($token);
            $cookies = \Yii::$app->response->cookies;
            $cookies->add(new Cookie([
                'name' => 'configForPickAddress',
                'value' => $configForPickAddress,
                'expire'=> time()+7000
            ]));
        }else {
            $cookies = \Yii::$app->response->cookies;
            $cookies->remove('configForPickAddress');
        }


        return  $this->render('addaddr',[
            'list'=>$address,
            'parameters'=>isset($configForPickAddress) ? $configForPickAddress :0,
        ]);
    }



    //获取用户卡券
    function actionCoupons(){
         $this->layout=false;
        $user_id = $this->getUserId();
        $status = 3;
        if (empty($user_id)) {
            WebBaseController::getAjaxData(2,'未传递用户ID');
        }
        //获取用户获取的卡券信息
        $ret = CouponsGroupService::getStatus($user_id,$status);
        $ret = ArrayHelper::toArray($ret['message']);
        //根据卡券组id,获取卡券活动的具体信息
        $groupInfo = [];
        if(isset($ret)&&$ret){
            foreach ($ret as $k=>$v) {
                if(is_array($ret[$k])){
                    $ret[$k] = CouponsGroupService::getGroupInfo($v['group_id']);
                    $data['type'] = $ret[$k]['result'][0]['type'];
                    $data['coupons_status'] = $v['status'];
                    $data['coupons_id'] = $v['coupons_id'];
                    $data['groupInfo'] = $ret[$k]['result'][0];
                    array_push($groupInfo,$data);
                }
            }
            $groupInfo = ArrayHelper::toArray($groupInfo);
        }

        return $this->render('coupon', [
            'coupons' => $groupInfo,
        ]);
    }


    //添加地址
    function actionAddaddrinfo(){
        if (Yii::$app->request->isAjax) {
            $getPost = yii::$app->request->post();
            $getPost['user_id'] = $this->getUserId();
            if(!preg_match('/^0?1[3|4|5|7|8][0-9]\d{8}$/',$getPost['mobile'])){
                echo 2;
                exit;
            }
            OrderUserService::addAddress($getPost);

            echo 1;
            exit;
        }else{
            return $this->render('addaddrinfo');
        }
    }

    //编辑地址
    function actionEditaddrinfo(){
        if (Yii::$app->request->isAjax) {
            $getPost = yii::$app->request->post();
            $getPost['dist_cn_char'] = $getPost['district_char'];
            $getPost['tel']='0';
            OrderUserService::update($getPost);
            echo 9;
            exit;
        }

        $id = yii::$app->request->get('id');
        if(empty($_SESSION['aidid'])){
            Yii::$app->session->set('aidid',$id);
            $data['id'] = $id;
        }else{
            $data['id'] =  Yii::$app->session->get('aidid');
        }
        $data['getByWeb']=1;
        $info = OrderUserService::search($data);
        if(isset($info)){
            $address = ArrayHelper::toArray($info['result']);
            foreach($address as $k=>$v){
                if(isset($v)){
                    if(isset($v['district'])&&$v['district']==0){
                        $address[$k]['merger']=$address[$k]['dist_cn_char'];
                        $address[$k]['district_char'] = '';
                    }else{
                        $addrRes = isset($v['district']) ? self::getDistrict_char($v['district']):'';
                        $address[$k]['district_char'] = isset($addrRes['district_char'])?$addrRes['district_char']:"";
                        $address[$k]['merger'] = isset($addrRes['merger']) ? $addrRes['merger']:'';
                    }
                }
            }
        }
        unset($_SESSION['aidid']);
        return $this->render('editaddrinfo',['address'=>$address]);

    }

    //添加自提地址
    function actionAddaddrself(){
        $type = Yii::$app->request->get('type');
        $address = ShopService::getAllAddress();
        $address = ArrayHelper::toArray($address);
        return $this->render('addaddrself',['list' => $address,'type'=>$type]);
    }

    //添加备注到cookie
    function actionAddremark(){
        $remark = Yii::$app->request->post('remark');
        $cookies = \Yii::$app->response->cookies;
        $cookies->add(new Cookie([
            'name' => 'remark',
            'value' => $remark
        ]));

    }

    //添加自选地址到cookie
    function actionSelectself(){
        $addr = Yii::$app->request->post('addr');
        $mobile = Yii::$app->request->post('mobile');
        $cookies = \Yii::$app->response->cookies;
        $cookies->add(new Cookie([
            'name' => 'addr',
            'value' => $addr,
        ]));
        $cookies->add(new Cookie([
            'name' => 'mobile',
            'value' => $mobile,
        ]));

    }

    //卡券加入cookie
    function actionGetcoupons(){
        $cookies = \Yii::$app->response->cookies;
        $voucher = Yii::$app->request->post('voucher');
        $conpons_id = Yii::$app->request->post('conpons_id');

        $cookies->add(new Cookie([
            'name' => 'voucher',
            'value' => $voucher,
        ]));

        $cookies->add(new Cookie([
            'name' => 'conpons_id',
            'value' => $conpons_id,
        ]));


        $total_price = Yii::$app->request->cookies->getValue('total_price') ?  Yii::$app->request->cookies->getValue('total_price') : '';
        $total_voucher = $total_price-$voucher;
        $total_voucher = WebBaseController::price_format($total_voucher);
        return $total_voucher;

    }

    //支付方式，配送方式，送货时间等添加到cookie
    function actionSeltag(){
        $tagid = Yii::$app->request->post('tagid');
        $cookies = Yii::$app->response->cookies;
        if($tagid==1){
            $cookies->add(new Cookie([
                'name' => 'onlinepay',
                'value' => '线上支付',
            ]));
            //销毁tokem
            $cookies->remove('addr');
            $cookies->remove('mobile');
            $cookies->remove('selfpersonal');
        }
        if($tagid==2){
            //销毁tokem
            $cookies->remove('onlinepay');
        }
        if($tagid==3){
            $cookies->add(new Cookie([
                'name' => 'delivery',
                'value' => '快递',
            ]));
            $cookies->remove('selfpersonal');
        }
        if($tagid==4){
            $cookies->add(new Cookie([
                'name' => 'selfpersonal',
                'value' => '自提',
            ]));
            $cookies->remove('delivery');
        }
        if($tagid==5){
            $cookies->add(new Cookie([
                'name' => 'workday',
                'value' => '只工作日送货',
            ]));
            $cookies->remove('weekday');
        }
        if($tagid==6){
            $cookies->add(new Cookie([
                'name' => 'weekday',
                'value' => '只双休日、节假日送货',
            ]));
            $cookies->remove('workday');
        }


    }

    //是否取消的地址是否是默认收货地址，
    function actionIsremoveaddr(){
        $data['id'] = yii::$app->request->post('addid');
        $data['getByWeb']=1;
        $info = OrderUserService::search($data);
        if(isset($info)){
            $address = ArrayHelper::toArray($info['result']);
            return json_encode($address[0]);
        }

    }

    /**
     * get char
     * @return mixed
     * 获取地址具体信息
     */
    private static function getDistrict_char($district) {
        $pro = substr($district, 0 , 2);
        $city = substr($district, 0 , 4);
        $merger_name = RegionService::getMesgerName($district);
        $nameArr = explode(',', $merger_name);
        $ret['district_char'] = $pro . '|' . $city . '|' . $district . ',' . $nameArr[1] . '|' . $nameArr[2] . '|' . $nameArr[3];
        $ret['merger'] =  $nameArr[1] . '|' . $nameArr[2] . '|' . $nameArr[3];
        return $ret;
    }

    /**
     * 回调url
     */
    function getUrl(){
        $redirect_uri =  'http://'.$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'];
        return $redirect_uri;
    }

    //创建签名SHA1
    function genSha1Sign($Parameters){
        $signPars = '';
        ksort($Parameters);
        foreach($Parameters as $k => $v) {
            if("" != $v && "sign" != $k) {
                if($signPars == '')
                    $signPars .= $k . "=" . $v;
                else
                    $signPars .=  "&". $k . "=" . $v;
            }
        }
        //$signPars = http_build_query($Parameters);
        $sign = SHA1($signPars);
        $Parameters['sign'] = $sign;
        return $sign;
    }


    function getPromotion($data){
        foreach($data as $key=>$val){
            $data[$key]= CouponsGroupService::getGroupInfo($val);
            $data[$key]= isset($data[$key]['result']) ? ArrayHelper::toArray($data[$key]['result']) : '';
            if(count($data[$key][0])<2){
                unset($data[$key]);
            }
            if(isset($data[$key][0]['group_id'])){
                $data[$key][0]['counpos'] =  CouponsService::userCouponsInfo($data[$key][0]['group_id'],$this->getUserId());
                if(isset($data[$key][0]['counpos'])){
                    foreach($data[$key][0]['counpos'] as $k=>$v){
                       if(!is_array($v)){
                           unset($data[$key]);
                       }
                    }
                }
            }
        }
       return $data;

    }





    /**
     * @param $data
     * @return array
     */
    function getOrder($data){
        foreach($data as $k=>$v){
           $arr[] = explode(',',$v);
        }
        foreach($arr as $key => $val){
            $res[$key]['product_id'] = $val[0];
            $res[$key]['shop_id'] = $val[1];
        }
        return $res;
    }


    //获取用户卡券
    function getCoupins($data){
        foreach($data as $k=>$v){
            $arr[] = CouponsGroupService::getGroupInfo($v['group_id']);
        }
        foreach($arr as $key=>$val){
            $arr[$key]['result'] = ArrayHelper::toArray($val['result']);
            $arr[$key]['result']['discount'] = isset($arr[$key]['result']['discount']) ? unserialize($arr[$key]['result']['discount']) : '';
            $arr[$key]['result']['product_id'] = isset($arr[$key]['result']['product_id']) ?unserialize($arr[$key]['result']['product_id']) : '';
        }
        return $arr;
    }


    /**
     * 结算
     * 前台参数格式：如两个商品 $cartProduct[0]=array('product_id'=> '131411','num'=>'1','data'=> '15151'),
     */
    public function submit($data)
    {
        $total_price = 0;
        foreach ($data as $k=>$v) {
            $data[$k]['price'] = ProductService::getPrice($v['product_id']);
            $data[$k]['price'] = ArrayHelper::toArray($data[$k]['price']);
            $data[$k]['price'] = $data[$k]['price']['price'];
            $total_price = $total_price + ($data[$k]['price'] * $data[$k]['num']);
        }
        return ['data' => $data, 'total_price' => $total_price];
    }

    /**
     * Lists all OrderModel models.
     * @return mixed
     * 订单列表
     * param用户id
     * 订单状态 0:待支付 1:待出库 2:已支付 3:待发货 4:已发货,等待收货
     * -1:供应商作废 -2:客户作废 -3:系统作废 -4:全部退货 -5:部分退货 -6:待审核 -7:退款
     * $arr = array(
        array(
            'oid'=>'10001', 'onum' => '10106546210', 'type'=> 1, 'list'=> array(
            '102' => array('title'=>'BOSS 佩戴时耳机', 'price'=> '888', 'attr'=>'颜色: 灰色', 'img'=>'img/tmp002.jpg'),
            '103' => array('title'=>'BOSS 佩戴时耳机', 'price'=> '888', 'attr'=>'颜色: 灰色', 'img'=>'img/tmp002.jpg')
            )
        ),
    );
     */
    public function actionIndex()
    {
        $data = yii::$app->request->get();
        $data['customer_id'] = $this->getUserId();
        $data['orderToC'] = 1;
        $data['getByWeb']=1;
        $type = yii::$app->request->get('status','');
        if($type==1){
            $data['status']=0;
        }
        if($type==2){
            $data['status']='4';
        }
        if($type==3){
            $data['status']='5';
        }

        $info = OrderService::findOrder($data);
        $info['result'] = ArrayHelper::toArray($info['result']);
        foreach($info['result'] as $k=>$v){
            $info['result'][$k]['orderItem'] = isset($v['order_id']) ?OrderService::findItems(['order_id'=>$v['order_id'],'getByWeb'=>1]) :array();
            $info['result'][$k]['orderItem'] = ArrayHelper::toArray($info['result'][$k]['orderItem']);
        }
        $arr=[];
        foreach($info['result'] as $key=>$val){
            $arr[$key]['oid'] = $val['order_id'];
            $arr[$key]['onum'] = $val['order_char_id'];
            $arr[$key]['type'] = $val['status'];
            $arr[$key]['product_id'] =$val['orderItem'][0]['product_id'];
            $arr[$key]['orderType'] = $this->getOrderType($val['status']);
            $arr[$key]['list']= $this->getProductAttr($val['orderItem'],$val['discount']);
        }


        return $this->render('index',['list'=>$arr,'type'=>$type]);
    }

    /**
     * 商品订单操作类型
     */
    function getOrderType($type){
        $arr = array(
            0=>'待付款',
            2=>'已支付',
            4=>'待收货',
            5=>'待评价',
            6=>'已评论'
        );

        $arrs = array(
            0=>'取消订单',
            4=>'查看物流',
            5=>'删除订单',
        );

        $arrss = array(
            0=>'付款',
            5=>'评价'
        );


        $res='';

       foreach($arr as $k=>$v){
           if($k==$type){
               $res[] = $v;
           }
       }
        foreach($arrs as $key=>$val){
            if($key==$type){
                $res[] = $val;
            }
        }

        foreach($arrss as $key3=>$val3){
            if($key3==$type){
                $res[] = $val3;
            }
        }
        return $res;
    }

    /**
     * @return string查看订单接口
     */
    public function actionAjaxorder()
    {
        $data = yii::$app->request->get();
        $data['customer_id'] = $this->getUserId();
        $data['funcName'] = $data['callback'];
        $status = yii::$app->request->get('type');
        $data['getByWeb']=1;
        if($status==1){
            $data['status']=0;
        }
        if($status==2){
            $data['status']='4';
        }
        if($status==3){
            $data['status']='5';
        }
        $data['orderToC'] = 1;
        $info = OrderService::findOrder($data);
        $info['result'] = ArrayHelper::toArray($info['result']);
        foreach($info['result'] as $k=>$v){
            $info['result'][$k]['orderItem'] = isset($v['order_id']) ?OrderService::findItems(['order_id'=>$v['order_id'],'getByWeb'=>1]) :array();
            $info['result'][$k]['orderItem'] = ArrayHelper::toArray($info['result'][$k]['orderItem']);
        }
        $arr = [];
        foreach($info['result'] as $key=>$val){
            $arr[$key]['oid'] = $val['order_id'];
            $arr[$key]['onum'] = isset($val['order_char_id'])?$val['order_char_id']:'';
            $arr[$key]['type'] =$val['status'];
            $arr[$key]['product_id'] =$val['orderItem'][0]['product_id'];
            $arr[$key]['list']= $this->getProductAttr($val['orderItem'],$val['discount']);
        }
         WebBaseController::getAjaxData(1,'获取成功',$arr,$data['funcName']);
    }


    //组装商品
    function getProductAttr($data,$discount){
        $arr=[];
        foreach($data as $k=>$v){
            $arr[$v['product_id']]['title'] = WebBaseController::msubstr($v['product_title'],0,30);
            $arr[$v['product_id']]['price'] = $v['price'];
            $arr[$v['product_id']]['attr'] = isset($v['data']) ? $this->setAttr($v['data'],$v['buy_num'],$discount) : '';
            $arr[$v['product_id']]['img'] = $v['product_pic_url'];
            $arr[$v['product_id']]['product_id'] = $v['product_id'];
        }
        return $arr;
    }

    /**
     * 获取价格 本来可以写成一个方法，但是这个方法是后写的
     */
    function getProoduct($pid){
        $res = ProductService::ProductInfo($pid);
        if($res['result']){
            $res['result'] = ArrayHelper::toArray($res['result']);
            $arr = isset($res['result']['productInfo']['price']) ? $res['result']['productInfo']['price'] : "";
        }
        return $arr;
    }

    /**
     * 组合属性
     */
    function setAttr($data,$buy_num,$discount){
//        elseif($discount){
//            $res.='数量:'.$buy_num.'<br/>优惠:'.$discount;
//        }
        $res='';
        if($data){
            foreach($data as $k=>$v){
                $res.=$k.':'.$v.'<br/>';
            }
            $res.='数量:'.$buy_num;
        }else{
             $res.='数量:'.$buy_num;
        }
        return $res;
    }


    /**
     * 组合属性
     * <em>颜色：</em><i>蓝红</i>
    <em>尺码：</em><i>S</i>
    <em>数量：</em><i>1</i>
     */
    function setAttrOrder($data){
        $res='';
        unset($data['product_id']);
        foreach($data as $k=>$v){
            $res.='<em>'.$k.':</em><i>'.$v.'</i>';
        }
        return $res;
    }



    /**
     * 根据线上线下选择收货地址
     */
    function actionSetsite(){
        $res['siteid'] = intval(yii::$app->request->post('siteid'));
        $res['shopid'] = intval(yii::$app->request->post('shopid'));
        $res['uid'] = $this->getUserId();
        $res['default'] = 1; //1是默认地址 0不是
        $res['getByWeb']=1;
        //1用户线上购买地址,2线下支付
        if($res['siteid']==1){
            $userSite = OrderUserService::search($res);
            $userSite['result'] = ArrayHelper::toArray($userSite['result']);
            $list['user_site'] =  $userSite['result'];
        }else{
            $info = ShopService::getAddress($res['shopid']);
        }

    }



    /**
     * 插入订单
     * $data = [
    0 => [
    'seller_id' => 1000001059,
    'customer_id' => 1,
    'channel_source' => 1,
    'device_source' => 1,
    'order_users_id' => 4,
    'remark' => '备注信息000',
    'express' => [
        name => 八个字
        district => 1024
        address => 宜山路200号518室
        tel => 13112345678
        mobile => 56131214
     ]
    'item' => [
        0 => [
        'product_id' => '603614611',
        'price' => 22.33,
        'buy_num' => 2,
        'data' => [
        'color' => '红色',
        'size' => '大',
        ]
        ],
        1 => [
        'product_id' => '603614611',
        'price' => 22.33,
        'buy_num' => 10,
        'data' => [
        'color' => '红色',
        'size' => '大',
        ]
        ],
    ]
    ]
    ];

     */
    function actionCreate(){
        //订单表
        $data=yii::$app->request->post();
        if(!$data['express']){
            WebBaseController::getAjaxDataInfo(4,'请选择快递');
        }
        if(!$data['pay']){
            WebBaseController::getAjaxDataInfo(5,'请选择支付方式');
        }
        if(!$data['express_time']){
            WebBaseController::getAjaxDataInfo(6,'请选择送货时间');
        }
        if(!$data['address']){
            WebBaseController::getAjaxDataInfo(12,'请填写收货地址');
        }

        //从购物车提交
        if(isset($data['shop_id'])){
            foreach($data['shop_id'] as $k=>$v){
                $info[$k]['shop_id'] = $v;
                $info[$k]['product_id']  = $data['pid'][$k];
            }
        }

        if($data['hide_buy']){
            foreach($info as $k=>$v){
                $goods[$k]['product_id'] = $v['product_id'];
                $goods[$k]['buy_num'] = $data['buy_num'];
                $goods[$k]['stock'] = $data['buy_num'];
                $pro= ProductService::ProductInfo($v['product_id']);

                $pro['result']['productInfo'] = ArrayHelper::toArray($pro['result']['productInfo']);
                //判断库存是否存在或者小于购买数量
                if(isset($pro['result']['productInfo'])&&$pro['result']['productInfo']){
                    if($pro['result']['productInfo']['stock']<=0 || $pro['result']['productInfo']['stock']<$data['buy_num']){
                        $list['status'] = 7;
                        $list['message'] =  '库存不足';
                        $list['pid'] =  $v['product_id'];
                        return \GuzzleHttp\json_encode($list);
                    }
                }

                $pro =  $pro['result']['productInfo'];
                $goods[$k]['price'] = $pro['price'];
                $goods[$k]['name'] = $pro['name'];
                $goods[$k]['thumb'] = isset($pro['thumb'][0])? $pro['thumb'][0] . '@1e_1c_0o_0l_200h_200w_100q.jpg':"";
                $goods[$k]['data'] =isset($pro['item_attrText_map'])?$this->getProductStr($v['product_id']):"";

            }
        }else{
            foreach($info as $k=>$v){
                $cartInfo[] = CartService::oneInfo($v['shop_id'],$this->getUserId(),$v['product_id']);
            }


            foreach($cartInfo as $k=>$v){
                $goods[$k] = unserialize($v['data']);
                $goods[$k]['product_id'] = $v['product_id'];
                $goods[$k]['thumb'] = isset($goods[$k]['thumb'][0]) ? $goods[$k]['thumb'][0]. '@1e_1c_0o_0l_200h_200w_100q.jpg':'';
                $goods[$k]['item_attrText_map'] = isset($goods[$k]['item_attrText_map']) ?$goods[$k]['item_attrText_map']: '';
                $goods[$k]['data'] = $goods[$k]['item_attrText_map'];
                unset($goods[$k]['item_attrText_map']);
                $pro= ProductService::ProductInfo($v['product_id']);

                $pro['result']['productInfo'] = ArrayHelper::toArray($pro['result']['productInfo']);
                //判断库存是否存在或者小于购买数量
                if(isset($pro['result']['productInfo'])&&$pro['result']['productInfo']){
                    if($pro['result']['productInfo']['stock']<=0 || $pro['result']['productInfo']['stock']<$v['num']){
                        $list['status'] = 8;
                        $list['message'] =  $pro['result']['productInfo']['name'].'库存不足';
                        return \GuzzleHttp\json_encode($list);
                    }
                }
                $goods[$k]['buy_num'] = $v['num'];
                $goods[$k]['price'] = ProductService::ProductInfo($v['product_id']);
                $goods[$k]['price'] = ArrayHelper::toArray($goods[$k]['price']['result']);
                $goods[$k]['price'] = isset($goods[$k]['price']['productInfo']['price']) ? $goods[$k]['price']['productInfo']['price']:'';
                $goods[$k]['price'] = $goods[$k]['price'];
                $goods[$k]['name'] = ProductService::ProductInfo($v['product_id']);
                $goods[$k]['name'] = ArrayHelper::toArray($goods[$k]['name']['result']);
                $goods[$k]['name'] = isset($goods[$k]['name']['productInfo']['name'])?$goods[$k]['name']['productInfo']['name']:'';
                $goods[$k]['name'] = $goods[$k]['name'];
            }
        }


        $arr['seller_id'] = 100101;
        $arr['customer_id'] = $this->getUserId();

        if($data['remark']){
            $cookies = \Yii::$app->response->cookies;
            $cookies->add(new Cookie([
                'name' => 'remark',
                'value' => $data['remark'],
            ]));
        }else{
            //get过来读取的cookie
            $data['remark'] = Yii::$app->request->cookies->getValue('remark');
        }

        $arr['remark'] = $data['remark'];  //留言

        $arr['order_users_id'] = $data['address']?$data['address']:0; //送货地址
        $res['getByWeb']=1;
        $res['id'] = $arr['order_users_id'];
        $address_info = OrderUserService::search($res);
        $userSite['result'] = ArrayHelper::toArray($address_info['result']);
        $userSite['result'][0]['pickup']=$data['express']; //选择快递
        $userSite['result'][0]['pickup_time']=$data['express_time']; //送货时间
        $userSite['result'][0]['express_self'] =  $data['express_self'];  //自提地址
        //卡券
        $arr['use_coupons']=  array(
            0=>array(
                'coupons_id'=> Yii::$app->request->cookies->getValue('conpons_id') ?  Yii::$app->request->cookies->getValue('conpons_id'):'',
                'coupons'=> Yii::$app->request->cookies->getValue('voucher') ?  Yii::$app->request->cookies->getValue('voucher') : 0
            )
        );
        $arr['discount'] = Yii::$app->request->cookies->getValue('voucher') ?  Yii::$app->request->cookies->getValue('voucher') : 0;
        $arr['express'] = $userSite['result'][0];   //快递信息和收货人地址
        $arr['payment_type'] = $data['pay'];  //支付方式
        $arr['channel_source'] = 1; //订单渠道来源
        $arr['device_source'] =1; //订单来源设备
        $arr['item'] = $goods;
        $arrs[] = $arr;
        $services = new OrderService();
        $p = $services->placeOrder($arrs);
        if($p['code']==1){
            return \GuzzleHttp\json_encode(2);
        }

        //更改卡券状态
        if(isset($data['coupons_id'])&&$data['coupons_id']){
            CouponsGroupService::changeOne($data['coupons_id'],4);
        }

        //删除购物车里的该商品
        foreach($info as $item){
            if($item){
                CartService::deleteProduct($item['shop_id'],$this->getUserId(),$item['product_id']);
            }
        }
        $goodsorder['order_id'] =  $p['result']['order_id'];
        $goodsorder['getByWeb']=1;
        $goodsList = OrderService::findItems($goodsorder);
        foreach($goodsList as $key=>$val){
            $stock[$val['product_id']] = $this->getBuyStock($val['product_id'],$val['buy_num'],1);
        }

        foreach($stock as $stkey=>$stval){
            ProductService::updateStock($stkey,$stval);
        }

        //销毁tokem
        $cookies = Yii::$app->response->cookies;
        $cookies->remove('order');
        $cookies->remove('addr');
        $cookies->remove('addressinfo');
        $cookies->remove('mobile');
        $cookies->remove('selfpersonal');
        $cookies->remove('delivery');
        $cookies->remove('workday');
        $cookies->remove('weekday');
        $cookies->remove('remark');
        $cookies->remove('user');
        $cookies->remove('voucher');
        $cookies->remove('conpons_id');


        $list['order_id']  = $p['result']['order_id'];
        $list['pay_type']  = $data['pay'];
        $list['status'] = 1;
        return \GuzzleHttp\json_encode($list);
    }

    function getProductStr($pid){
        $res=$rest=$rr=[];
        $goodsDetail = ProductService::ProductInfo($pid);
        $arr= ArrayHelper::toArray($goodsDetail['result']['productInfo']);
        if(isset($arr['item_url_map'])){
            foreach($arr['item_url_map'] as $k=>$v){
                if($pid==$v['product_id']){
                    $res = isset($arr['item_url_map'][$k])?$arr['item_url_map'][$k]:array();
                    unset($res['product_id']);
                }
            }
            return $res;
        }
    }

    /**
     * 取消订单
     * status=-2
     */
    function actionCancelorder(){
        $data = yii::$app->request->get();
        if(!$data['cancel_order']){
            WebBaseController::getAjaxData(2,'订单不存在');
        }
       $res[0]['order_id'] = intval($data['cancel_order']);
       $res[0]['status']='-2';

       $info =  OrderService::changeStatus($res);
       if($info['code']==1){
           WebBaseController::getAjaxData(3,'错误操作');
       }

        //更改卡券状态
        $info['order_id'] = $res[0]['order_id'];
        $info['getByWeb'] = 1;
        $coupons = OrderService::findOrder($info);
        if(isset($coupons['result'][0])&&$coupons['result'][0]){
            $coupons = ArrayHelper::toArray($coupons['result'][0]);
        }
        if(isset($coupons['use_coupons']['0']['coupons_id'])&&$coupons['use_coupons']['0']['coupons_id']){
            $couponsId = $coupons['use_coupons']['0']['coupons_id'];
            CouponsGroupService::changeOne($couponsId,3);
        }



        if($info['code']==0){
            $rest['order_id'] = intval($data['cancel_order']);
            $rest['getByWeb']=1;
            $orders = OrderService::findItems($rest);
            $orders= ArrayHelper::toArray($orders);
            foreach($orders as $key=>$val){
                $stock[$val['product_id']] = $this->getBuyStock($val['product_id'],$val['buy_num'],2);
            }
            foreach($stock as $stkey=>$stval){
                ProductService::updateStock($stkey,$stval);
            }
            WebBaseController::getAjaxData(1,'操作成功','',$data['callback']);
        }


    }

    function getBuyStock($pid,$num,$type=''){
        $goodsDetail = ProductService::ProductInfo($pid);
        $arr= ArrayHelper::toArray($goodsDetail['result']['productInfo']);

        if($type==1){
            $stock = $arr['stock']-$num;
        }elseif($type==2){
            $stock = $arr['stock']+$num;
        }
        return $stock;
    }
    /**
     *删除订单
     * is_hidel=1
     */
    function actionDelorder(){
        $data = yii::$app->request->get();
        if(!$data['del_order']){
            WebBaseController::getAjaxData(2,'订单不存在');
        }
        $res['order_id'] = intval($data['del_order']);
        $info =  OrderService::toHide($res);
        if($info['code']==1){
            WebBaseController::getAjaxData(3,'错误操作');
        }
        WebBaseController::getAjaxData(1,'操作成功','',$data['callback']);

    }

    /**
     * 自提地址提交成功
     */
    function actionConfirminfo(){
        $data = yii::$app->request->get();

        if(!isset($data['order_id'])){
            return false;
        }
        //查询卡券信息


        if (Yii::$app->request->isAjax) {
            $getPost = yii::$app->request->post();
            $data['order_id'] = $getPost['order_id'];
            $data['express']['name'] = $getPost['name'];
            $data['express']['mobile'] = $getPost['mobile'];
            $result = OrderService::updateExpressInfo($data);
            if($result['code']==0){
                return 1;
            }

        }else{
            $data['getByWeb']=1;
            $arr = OrderService::findOrder($data);
            $arr['result'] = ArrayHelper::toArray($arr['result']);
            $orders=[];
            foreach($arr['result'] as $k=>$v){
                $orders['order_id'] = $v['order_id']; //总价
                $orders['order_cost'] = $v['order_cost'];
                $orders['order_char_id'] = $v['order_char_id']; //总价
                $orders['remark'] = $v['remark'];
                $orders['express'] = $v['express'];
                $orders['item'] = OrderService::findItems($data);
                foreach($orders['item'] as $key=>$val){
                    $orders['item'][$key] = ArrayHelper::toArray($val);
                }
            }
            $orders['order_cost'] = WebBaseController::price_format($orders['order_cost']);
            return $this->render('confirminfo',[
                'list'=>$orders
            ]);
        }
    }

    //自提订单成功之后显示的页面
    public function actionOrdersuccess() {
        return $this->render('ordersuccess');
    }

    /**
     * 订单成功
     */
    public function actionPayment(){
        $data = yii::$app->request->get();

        if(!isset($data['order_id'])){
            return false;
        }

        if (empty($this->openId)) {
            $conf = AccountService::getWechatConfig(self::ORIGINAL_ID);
            $app = new Application($conf);
            $oauth = $app->oauth;
            $_SESSION['target_url'] = '/web/order/payment?order_id=' . $data['order_id'];
            $oauth->redirect()->send();
        }
       $data['getByWeb']=1;
       $arr = OrderService::findOrder($data);
       $arr['result'] = ArrayHelper::toArray($arr['result']);
       $orders=[];
       foreach($arr['result'] as $k=>$v){
           $orders['order_id'] = $v['order_id']; //总价
           $orders['order_cost'] = $v['order_cost']; //总价
           $orders['remark'] = $v['remark'];
           $orders['express'] = $v['express'];
           $orders['item'] = OrderService::findItems($data);
               foreach($orders['item'] as $key=>$val){
                   $orders['item'][$key] = ArrayHelper::toArray($val);
               }
       }

        $orders['order_cost'] = WebBaseController::price_format($orders['order_cost']);
        $body = "";
        $product_title = "";
        $orderItem = $orders['item'];

        if (sizeof($orderItem) == 1) {
            $body = self::title_substr($orderItem[0]['product_title'],15);
            $product_title = $orderItem[0]['product_title'];
        }else if (sizeof($orderItem) > 1) {
            $body = self::title_substr($orderItem[0]['product_title'],13) . " 及其他" . sizeof($orderItem) . "件商品";
            $product_title = $orderItem[0]['product_title'];
            for ($i = 1 ; $i <= sizeof($orderItem) - 1; $i++) {
                $product_title .= "<br/> + " . $orderItem[$i]['product_title'];
            }
        }

        return $this->render('payment',[
            'totalprice' => $orders['order_cost'],
            'body' => $product_title,
            'payment' =>  $this->pay($body, $orders['order_id'], $orders['order_cost']*100)
        ]);
    }

    //支付成功之后显示的页面
    public function actionSuccess() {
        return $this->render('success');
    }

    //创建签名SHA1
    private function getSha1Sign($Parameters){
        $signPars = '';
        ksort($Parameters);
        foreach($Parameters as $k => $v) {
            if("" != $v && "sign" != $k) {
                if($signPars == '')
                    $signPars .= $k . "=" . $v;
                else
                    $signPars .=  "&". $k . "=" . $v;
            }
        }
        //$signPars = http_build_query($Parameters);
        $sign = SHA1($signPars);
        $Parameters['sign'] = $sign;
        return $sign;
    }

    //控制标题长度
    private function title_substr($title,$long) {
        $pa = '/./us';
        preg_match_all($pa, $title, $r);
        $count = count($r[0]);
        if ($count > $long) {
            $title = mb_substr($title,0,$long,'utf-8')."...";
        }
        return $title;
    }

    //支付相关
    private function pay($body, $orderId, $totalPrice)
    {
        $callback_url = 'http://shopbox.10000dt.com/web/pay/notify_3';

        $options = [
            'app_id' => $this->_appId,
            'payment' => [
                'merchant_id'        => $this->_mch_id,
                'key'                => $this->_mch_key,
//                'cert_path'          => 'path/to/your/cert.pem', // XXX: 绝对路径！！！！
//                'key_path'           => 'path/to/your/key',      // XXX: 绝对路径！！！！
                'notify_url'         => $callback_url,       // 你也可以在下单时单独设置来想覆盖它
            ],
        ];

        $app = new Application($options);
        $payment = $app->payment;


        $attributes = [
            'body' => $body,
            'detail' => $body,
            'out_trade_no' => $orderId,
            'total_fee' => $totalPrice,
            'notify_url' => $callback_url, // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'trade_type' => 'JSAPI',
            'openid' => $this->openId//
        ];
        \Yii::info($attributes, "----------支付-----------");
        $order = new Order($attributes);

        $result = $payment->prepare($order);//

        $prepayId = $result->prepay_id;

        $json = $payment->configForPayment($prepayId);

        return $json;
    }

    //服务器调用的
    //7天前已发货，待收货的订单，统统变成已完成
    public function actionComplete_order() {
        $deadLine = time() - 86400 * 7; // 7天前的订单
        $order = Orders::findSendOrder(['status' => 4, 'deadLine' => $deadLine]);
        $order = ArrayHelper::toArray($order);

        if (!empty($order)) {
            foreach ($order as $k => $v) {
                $order[$k]['status'] = 5;
            }
            return json_encode(OrderService::changeStatus($order));
        }
        return ReturnHelper::success_json('success', 'no change');
    }

    //服务器调用的
    //2小时前没支付的订单，统统变成已取消
    public function actionCancel_order() {
        $deadLine = time() - 3600 * 2; // 2小时前的订单
        $order = Orders::findNeedPayOrder(['status' => 0, 'deadLine' => $deadLine]);
        $order = ArrayHelper::toArray($order);

        if (!empty($order)) {
            foreach ($order as $k => $v) {
                $order[$k]['status'] = -2;
            }
            $changeRes = OrderService::changeStatus($order);
            $stock = [];
            $errMsg = '';
            if ($changeRes['code'] == 0) {
                foreach ($order as $k => $v) {
                    //查出每个订单的商品
                    $rest['order_id'] = intval($order[$k]['order_id']);
                    $rest['getByWeb']=1;
                    $items = OrderService::findItems($rest);
                    $items = ArrayHelper::toArray($items);
                    //把订单里购买的商品数量返还给商家
                    foreach($items as $key=>$val){
                        $stock[$val['product_id']] = $this->getBuyStock($val['product_id'],$val['buy_num'],2);
                    }
                    //修改库存
                    foreach($stock as $stkey=>$stval){
                        $updateRes = ProductService::updateStock($stkey,$stval);
                        //若有修改失败的
                        if (!$updateRes) {
                            if ($errMsg == '') {
                                $errMsg = $stkey . '' . $stval;
                            }else {
                                $errMsg = ',' . $stkey . ':' . $stval;
                            }
                        }
                        continue;
                    }
                }
                if ($errMsg == '') {
                    return ReturnHelper::success_json('success');
                }else {
                    return ReturnHelper::error_json('"商品编号" : "商品数量" 未修改成功', $errMsg);
                }
            }
            return json_encode($changeRes);
        }
        return ReturnHelper::success_json('success', 'no change');
    }


    //服务器调用的
    //订单完成10天后，提醒用户评论
    private $comment_message = '亲爱的顾客！您的好评是对我们最大的支持哟~（请猛戳这里 http://shopbox.10000dt.com/web/order?status=3）';

    public function actionComment_message() {
        $deadLine = strtotime(date('Y-m-d 23:59:59', time())) - 86400 * 10; // 10天前的订单
        //查出发货时间是在10天以前的
        $order = Orders::findCompleteOrder(['status' => 5, 'deadLine' => $deadLine]);
        $order = ArrayHelper::toArray($order);
        $openId_array = [];
        foreach ($order as $k => $v) {
            if (!in_array($v['customer_id'], $openId_array)) {
                array_push($openId_array, $v['customer_id']);
            }
        }
        //向用户发送消息
        $useConfig = Account::getWechatConfigbyAid(7);
        $app = new Application($useConfig);

        $broadcast = $app->broadcast;

        $text = $this->comment_message;

        $result = [
            'successToSend' => [],
            'failToSend' => [],
        ];
        if (!empty($openId_array)) {
            foreach ($openId_array as $ok => $ov) {
                $openId = CustomerInfo::getOpenId($ov);
                if (!isset($openId)) {
                    continue;
                }
                $ret_msg = $broadcast->previewText($text, $openId);
                if ($ret_msg['errcode'] == 0) {
                    array_push($result['successToSend'], $openId);
                }else {
                    array_push($result['failToSend'], $openId);
                }
            }
        }

        return ReturnHelper::success_json('success', $result);
    }

}